package top.xmj.task;

import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import top.xmj.dao.SubMessageMapper;
import top.xmj.pojo.SubMessage;
import top.xmj.util.RedisUtil;

import javax.annotation.Resource;

@Slf4j
public class RedisToMysqlTask extends QuartzJobBean {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private SubMessageMapper subMessageMapper;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        // 获取存储在redis中聊天记录的条数
        long messageListSize = redisUtil.lGetListSize("subMessage");
        // 写入数据库的数据总条数
        long resultCount = 0;
        for (int i = 0; i < messageListSize; i++) {
            // 从头到尾取出链表中的元素
            SubMessage subMessage= (SubMessage) redisUtil.listPopLeftKey("subMessage");
            // 向数据库写入数据
            int result = subMessageMapper.insert(subMessage);
            if (result > 0) {
                // 写入成功
                resultCount++;
            }
        }
        log.info(resultCount+ "条聊天记录，已写入数据库");
    }
}
